package com.drd.dt.modular.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.baomidou.mybatisplus.plugins.Page;
import com.drd.dt.common.Constant;
import com.drd.dt.common.SuccessResultEnum;
import com.drd.dt.common.tips.Tip;
import com.drd.dt.exception.BizExceptionEnum;
import com.drd.dt.modular.EnumUtils.BusinessAcademyFirstEnum;
import com.drd.dt.modular.EnumUtils.BusinessAcademySecondEnum;
import com.drd.dt.modular.EnumUtils.BusinessAcademyThirdEnum;
import com.drd.dt.modular.dao.BusinessAcademyMapper;
import com.drd.dt.modular.dao.UserMapper;
import com.drd.dt.modular.dto.BusinessAcademyDTO;
import com.drd.dt.modular.dto.GoodsDetailDTO;
import com.drd.dt.modular.dto.PersonalCenterDTO;
import com.drd.dt.modular.entity.BusinessAcademy;
import com.drd.dt.modular.service.BusinessAcademyService;
import com.drd.dt.properties.HDKPropertyConfig;
import com.drd.dt.properties.PDDPropertyConfig;
import com.drd.dt.util.HttpConnectionPoolUtil;
import com.drd.dt.util.ResultUtil;
import com.drd.dt.util.StringUtil;
import com.pdd.pop.sdk.common.util.JsonUtil;
import com.pdd.pop.sdk.http.PopClient;
import com.pdd.pop.sdk.http.PopHttpClient;
import com.pdd.pop.sdk.http.api.request.PddDdkGoodsRecommendGetRequest;
import com.pdd.pop.sdk.http.api.request.PddDdkOauthGoodsRecommendGetRequest;
import com.pdd.pop.sdk.http.api.response.PddDdkGoodsRecommendGetResponse;
import com.pdd.pop.sdk.http.api.response.PddDdkOauthGoodsRecommendGetResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class BusinessAcademyServiceImpl implements BusinessAcademyService {
    private static final Logger logger = LoggerFactory.getLogger(BusinessAcademyServiceImpl.class);

    @Autowired
    private BusinessAcademyMapper businessAcademyMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private HDKPropertyConfig hdkPropertyConfig;
    @Autowired
    private PDDPropertyConfig pddPropertyConfig;

    @Override
    public Tip friendBusinessAcademym(BusinessAcademyDTO map) throws Exception {
        List<BusinessAcademy> all;
        int pageIndex = map.getPageIndex();
        int pageSize = map.getPageSize();
        int first_module = map.getFirst_module();
        int second_module = map.getSecond_module();
        Page page = new Page(pageIndex, pageSize);
        if (first_module == 1){//每日爆款
            if (second_module == 1){//淘宝
                JSONObject result = new JSONObject();
                List data = getRecommendGoodsInfoByHDK(pageIndex);
                result.put("datas",data);
                result.put("totalCounts",1000);
                return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), result);
            }
        }
        if (map.getFirst_module() == 3) {
            all = businessAcademyMapper.friendBusinessAcademymBriefness(page, map);
        } else {
            all = businessAcademyMapper.friendBusinessAcademym(page, map);
        }
        page.setRecords(all);
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), page);
    }

    @Override
    public Tip ifUserLevel(BusinessAcademyDTO map) {
        //1 如果是查看文章 校验 当前会员等级是否有权限
        String leve = userMapper.getUserLevel(map.getUser_id());
        BusinessAcademy businessAcademy = businessAcademyMapper.getCommodity(map.getBusiness_id());
        if (null != leve && !leve.equals("") && Integer.parseInt(leve) >= businessAcademy.getShow_lv()) {
            return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), businessAcademy);
        } else {//权限不足 返回提示
            return ResultUtil.result(BizExceptionEnum.BUSINESS_ACADEMY_AUTHORITY_LACK.getCode(), BizExceptionEnum.BUSINESS_ACADEMY_AUTHORITY_LACK.getMessage());
        }
    }

    @Override
    public Tip synchronizationAccumulativeTotal(BusinessAcademyDTO map) {

        int req = businessAcademyMapper.synchronizationAccumulativeTotal(map);
        if (req == 1) {
            return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage());
        } else {
            return ResultUtil.result(BizExceptionEnum.BUSINESS_ACADEMY_DATA_ADD_ERROR.getCode(), BizExceptionEnum.BUSINESS_ACADEMY_DATA_ADD_ERROR.getMessage());
        }
    }

    @Override
    public Tip getModelCorrelationGrouping(int first_module, int second_module,String app_version,HttpServletRequest request,int deviceT) throws Exception {
        //一级分组
        List<Map<String, String>> first_moduleList = new ArrayList<>();
        String version = userMapper.getVerifyVersion();//获取ios审核版本号
        List<String> firstModule = businessAcademyMapper.getFirstModule();
        //判断是否为国外ip
        String ip = StringUtil.getIpAddr(request);
        String country = new StringUtil().getIPLocation(ip);
        for (String str : firstModule) {
            if (!StringUtils.isEmpty(deviceT) && deviceT == 1){//ios
                if (app_version.equals(version) || country.equals("美国")){//ios 审核版过滤
                    if (!str.equals("1")){
                        continue;
                    }
                }
            }
            Map<String, String> m = new HashMap<>();
            m.put("type", str);
            String typeName = BusinessAcademyFirstEnum.getStrValue(Integer.parseInt(str));
            if (!typeName.equals("")) {
                m.put("typeName", typeName);
                first_moduleList.add(m);
            }
        }
        //2级分组
        List<Map<String, String>> second_moduleList = new ArrayList<>();
        List<String> secondModule = businessAcademyMapper.getSecondModule(first_module);
        if (first_module == 3) {
            secondModule = new ArrayList<String>();
            for (int i = 1; i <= 6; i++) {
                secondModule.add(i + "");
            }
        }
        for (String str : secondModule) {
            Map<String, String> m = new HashMap<>();
            m.put("type", str);
            String typeName = BusinessAcademySecondEnum.getStrValue(Integer.parseInt(str), first_module);
            if (!typeName.equals("")) {
                m.put("typeName", typeName);
                if (first_module == 3) {
                    String icon = BusinessAcademySecondEnum.getStrValueIcon(Integer.parseInt(str), first_module);
                    if (!icon.equals("")) {
                        m.put("typeIcon", icon);
                    }
                }
                second_moduleList.add(m);
            }
        }
        //3级分组
        List<Map<String, String>> third_moduleList = new ArrayList<>();
        for (String str : businessAcademyMapper.getThirdModule(first_module, second_module)) {
            Map<String, String> m = new HashMap<>();
            m.put("type", str);
            String typeName = BusinessAcademyThirdEnum.getStrValue(Integer.parseInt(str), second_module, first_module);
            if (!typeName.equals("")) {
                if (first_module == 2 && second_module == 2) {
                    m.put("typeName", "新人第" + typeName + "天");
                } else {
                    m.put("typeName", typeName);
                }
                third_moduleList.add(m);
            }
        }

        Map<String, Object> map = new HashMap<>();
        map.put("first_module", first_moduleList);
        map.put("second_module", second_moduleList);
        map.put("third_module", third_moduleList);
        return ResultUtil.result(SuccessResultEnum.ADD_SUCCESS.getCode(), SuccessResultEnum.ADD_SUCCESS.getMessage(), map);
    }

    /**
     * 从好单库获取朋友圈商品推荐(淘宝每日爆款)
     */
    private List getRecommendGoodsInfoByHDK(Integer min_id){
        String apikey = hdkPropertyConfig.getApiKey();
        String hdk_url = hdkPropertyConfig.getMomentsUrl() + "apikey/" + apikey+ "/min_id/" + min_id;
        String dataStr = HttpConnectionPoolUtil.get(hdk_url);
        List list = new ArrayList();
        SimpleDateFormat fmt = Constant.y_M_d;
        if (!StringUtils.isEmpty(dataStr)){
            JSONObject str = JSON.parseObject(dataStr, Feature.DisableSpecialKeyDetect);
            JSONArray datas = str.getJSONArray("data");
            Random random = new Random();
            for (int i = 0; i < datas.size() ; i ++){
                Map map= new HashMap();
                Object obj = datas.get(i);
                String content = JSON.parseObject(JSON.toJSONString(obj)).getString("content");//单品导购内容
                String show_comment = JSON.parseObject(JSON.toJSONString(obj)).getString("show_comment");//导购文案展示内容，含表情
                String copy_content = JSON.parseObject(JSON.toJSONString(obj)).getString("copy_content");
                String couponurl = JSON.parseObject(JSON.toJSONString(obj)).getString("couponurl");
                String couponmoney = JSON.parseObject(JSON.toJSONString(obj)).getString("couponmoney");//优惠券金额
                JSONArray itempics = JSON.parseObject(JSON.toJSONString(obj)).getJSONArray("itempic");
                String goods_id = JSON.parseObject(JSON.toJSONString(obj)).getString("itemid");//单品id
                String show_time = JSON.parseObject(JSON.toJSONString(obj)).getString("show_time");//时间戳
                String title = JSON.parseObject(JSON.toJSONString(obj)).getString("title");

                Date date = new Date(new Long(show_time) * 1000);
                String time = fmt.format(date);
                String cont = content.replaceAll("[$emoji表情]","").replaceAll("\\[.*?\\]","");
                map.put("text",cont);
                map.put("biz_id",goods_id);//商品Id
                map.put("create_time",time);
                map.put("type",1);
                map.put("video","");
                map.put("home_image","https://meimg.su.bcebos.com/htsq/htsq_icon.png");
                map.put("title","核桃省钱");
                map.put("transpond_num",random.nextInt(11000)+10000);
                if (!StringUtils.isEmpty(couponurl) && !StringUtils.isEmpty(couponmoney) && Double.valueOf(couponmoney) > 0){
                    map.put("ifcoupon",1);
                }else {
                    map.put("ifcoupon",0);
                }
                int size = itempics.size();
                if (size > 6 && size < 9){
                    size = 5;
                }else if (size > 3 && size < 6){
                    size = 3;
                }
                String[] pictureArr = new String[size];
                for (int k = 0; k < size; k ++){
                    String pic = String.valueOf(itempics.get(k));
                    //由于图片原图过大影响加载速度，建议加上后缀_310x310.jpg
                    pictureArr[k] = pic ;
                }
                map.put("ima_sList",pictureArr);
                list.add(map);
            }
        }
        return list;
    }

}
